package com.itheima.springboottlias.service.impl;

import Pojo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.itheima.springboottlias.Util.JwtUtils;
import com.itheima.springboottlias.anno.LogOperation;
import com.itheima.springboottlias.exception.PasswordException;
import com.itheima.springboottlias.exception.UserNameException;
import com.itheima.springboottlias.mapper.EmpExprMapper;
import com.itheima.springboottlias.mapper.EmpMapper;
import com.itheima.springboottlias.service.EmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl  implements EmpService {
    private static final Logger log = LoggerFactory.getLogger(EmpServiceImpl.class);
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogServiceImpl empLogService;//注入操作日志
    //分页和条件查询
    @Override
    public PageResult page(EmpQueryParam queryParam) {
     /*   //1.查询指定页数的数据
        //计算起始位置
        int start = (queryParam.getPage() - 1) * queryParam.getPageSize();
        queryParam.setPage(start);//将页码改成起始位置
         List<EmpQueryParam> empQueryParams = empMapper.selectPage(queryParam);
        //2.查询总记录数
        Long  count =empMapper.count(queryParam);
        //3.封装查询的两个结果并返回数据
        */


        //1.使用分页插件实现分页查询
        //1.1启用分页插件
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());
        //1.2调用被分页查询插件增强的持久层方法
        Page<Emp> page = (Page<Emp>) empMapper.selectByCondition(queryParam);

        //1.3从分页插件增强方法的返回结果中获取数据封装到PageResult中返回
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

        return pageResult;
    }
    //查询所有员工
    @Override
    public List<Emp> queryAllEmp() {
        return empMapper.queryAllEmp();
    }
    //添加员工(事务管理)
    @LogOperation
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addEmp(Emp emp) {
        try {
            //1.调用持久层方法完成添加
            //补充基础字段
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.addEmp(emp);
            //2.如果有工作经验，则添加到emp_expr表中
            List<EmpExpr> exprList = emp.getExprList();
            if (exprList != null && exprList.size() > 0) {
               //2.1设置当前员工经历的员工信息
                exprList.stream().forEach(expr -> expr.setEmpId(emp.getId()));

                //2.2调用持久层方法完成添加
                //方式一：循环添加
              /*  for (EmpExpr expr : exprList) {
                    empExprMapper.addEmpExpr(expr);
                }*/
                //方式二：批量添加
                empExprMapper.addEmpExprs(exprList);
            }
        } finally {
            //3.添加操作日志
            EmpLog empLog = new EmpLog(emp.getId(), LocalDateTime.now(), "添加员工");
            empLogService.insertLog(empLog);
        }
    }
    //删除员工和员工的工作经验
    @LogOperation
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByIds(List<Integer> ids) {
        //1.调用持久层方法删除员工
        //sql语句：delete from emp where id in (?,?,？。。。)
        empMapper.deleteByIds(ids);

        //2.调用持久层方法删除员工对应的工作经验
        //sql语句：delete from emp_expr where emp_id in (?,?,？。。。)
        empExprMapper.deleteByEmpIds(ids);

    }
    //查询员工详情

    @Override
    public Emp queryById(Integer id) {
        //方案一：两次单表查询
        //1.调用持久层方法查询员工详情(不含工作经验)
//        Emp emp=empMapper.queryById(id);

        //2.调用持久层方法根据员工id查询工作经验
//        List<EmpExpr> exprList = empExprMapper.queryByEmpId(id);
        //3.封装返回
//        emp.setExprList(exprList);
//        return emp;

        //方式二：一次多表查询（数据亮大，性能低）
        Emp emp = empMapper.queryByIdAndExprs(id);
        return emp;
    }
    //修改员工
    @LogOperation
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmp(Emp emp) {
        //1.调用持久层方法修改员工
        //同步更新时间
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateEmp(emp);
        //2.调用持久层方法删除员工对应的工作经验
        List<Integer> ids = new ArrayList<>();
        ids.add(emp.getId());
        log.info("选择的id"+ids);
        empExprMapper.deleteByEmpIds(ids);
        //3.添加员工对应的工作经验
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            //3.1设置当前员工经历的员工信息
            exprList.stream().forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.addEmpExprs(exprList);
        }

    }
    //登录
    @Override
    public LogInfor checkLogin(Emp emp) {
        Emp emp1 =  empMapper.checkLogin(emp);
        if (emp1!=null){
            //1.生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",emp1.getId());
            claims.put("username",emp1.getUsername());

            String jwt = JwtUtils.generateJwt(claims);
            LogInfor logInfor = new LogInfor(emp1.getId(), emp1.getUsername(), emp1.getPassword(), jwt);
            return logInfor;
        }

        return null;
    }


}
